#!/bin/bash
#
# This script allows generate statistics about the state 
# our internet connection from the log file 
# $DIRECTORY_LOG/internet_link_status.log. Then, this 
# statistics are stored in $DIRECTORY_LOG/stats/ 
#

# ---------------------------------------------------------
#   Load and check the configuration
# ---------------------------------------------------------

  # Load config file
  ConfigFile=/usr/local/TECNOQUIA/etc/dynIP.cfg
  if [ ! -e $ConfigFile ] || [ ! -r $ConfigFile ]
  then
     echo "ERROR: I can't read the config file [$ConfigFile]" >&2
     exit 5
  fi
  . $ConfigFile
    
  
  # Check the directory that i must save the log files
  if [ ! -w $DIRECTORY_LOG ]
  then
     echo "ERROR: I can't write into [$DIRECTORY_LOG]. Check that exists and the permissions on this directory" >&2
     exit 6
  fi
  # Create the report statistics directory
  BaseDir=$DIRECTORY_LOG/stats
  mkdir -p -m 777 $BaseDir

  # File with the activity internet link 
  logFile=$DIRECTORY_LOG/internet_link_status.log

  # For temporay files
  tmpFile=/tmp/dynIP_statistics-$$-$RANDOM

  # Get current time
  now=`date '+%s'`

# ---------------------------------------------------------
#   Functions
# ---------------------------------------------------------

check_ping() {
   for ip in $IP_CHECK_LIST
   do
      ping -c 1 $ip >/dev/null 2>&1  && return 0
   done
   return 1
}


get_velocity() {
   local ms="60000"
   for ip in $IP_CHECK_LIST
   do
      ms=`ping -c 3 $ip -q | grep 'min/avg' | perl -ne '{print $1 if($_=~m/\=\s+[^\/]+\/(\d+).*\//);}' `
      if [ "$ms" != "" ]
      then
         echo "$ms"
         return 
      fi 
   done
   echo "60000"
}



# ---------------------------------------------------------
#   M A I N
# ---------------------------------------------------------

  # Get current time in several formats
  nowDay=`date -d "@${now}" "+%Y%m%d"`
  nowDHour=`date -d "@${now}" "+%Y%m%d_%H"`
  nowLog=`date -d "@${now}"  "+%d/%h/%y  %H:" `

  # Get ping  response time (in ms). If the line is down, will obtain
  # too much time, 1 minute
  velocity=`get_velocity `

  # Chek current status 
  if check_ping 
  then
     echo "[`date "+%d/%h/%y  %H:%M:%S"`] [`date '+%s'`] (hearbeat) The internet link is UP" >> $logFile
  else
     echo "[`date "+%d/%h/%y  %H:%M:%S"`] [`date '+%s'`] (hearbeat) The internet link is DOWN" >> $logFile
  fi

  # Filter activity in this hour
  grep "$nowLog" $logFile | grep -e 'is UP' -e 'is DOWN' > $tmpFile.filtered


  # initialize some counters 
  counterChangesState=0
  counterTimeUp=0
  counterTimeDown=0
  firstTimeMark=$[ $now / 3600 * 3600 ]
  lastTimeMark=$firstTimeMark
  lastState=""

  # Read all lines in file 
  exec 9<  $tmpFile.filtered
  while read -u 9 line
  do
     # Get status in this line...
     curState=`echo $line | perl -ne 'print lc($1) if($_=~m/link is (\S+)/);' `
     curTimeMark=`echo $line | perl -ne 'print "$1" if($_=~m/\s+\[(\d+)\]\s/);' `
     
     if [ "" = "$lastState" ]
     then 
        # the last state is initial state.
        lastState=$curState
     else
        # Not is the first line from file
        passedTime=$[ $curTimeMark - $lastTimeMark ]

        # Check the status readed from line
        if [ "down" = "$curState" ] && [ "down" != "$lastState" ]
        then
            # Is a change: UP to DOWN
            lastState=$curState
            lastTimeMark=$curTimeMark
            
            # Accounting the time was UP
            counterTimeUp=$[ $counterTimeUp + $passedTime ]
            counterChangesState=$[ $counterChangesState + 1 ] 
        elif [ "down" = "$curState" ] && [ "down" != "$lastState" ]
        then
            # Is a change: DOWN to UP
            lastState=$curState
            lastTimeMark=$curTimeMark
            
            # Accounting the time was UP
            counterTimeDown=$[ $counterTimeDown + $passedTime ]
            counterChangesState=$[ $counterChangesState + 1 ] 
        fi 
     fi
  done
  exec 9<&- 
  
  # Sumarize last status
  passedTime=$[ $curTimeMark - $lastTimeMark ]
  if [ "down" = "$curState" ]
  then
     counterTimeDown=$[ $counterTimeDown + $passedTime ]
  else
     counterTimeUp=$[ $counterTimeUp + $passedTime ]
  fi

  # Calculate the percent time was up
  if [ $lastTimeMark -eq  $firstTimeMark ]
  then
     TotalTime=$passedTime
  else
     TotalTime=$[ $lastTimeMark - $firstTimeMark  ]
  fi

  PercentTimeUp=0
  [ $TotalTime -gt 0 ] && PercentTimeUp=$[ 100 * $counterTimeUp / $TotalTime ] 

  # Write statistics into file-hourly
  cat >$BaseDir/stats_hourly_$nowDHour.log <<EOF
State changes = $counterChangesState 
Seconds link up = $counterTimeUp
Seconds link down = $counterTimeDown
Percent link up = $PercentTimeUp
Milliseconds response time = $velocity
EOF

 
  # Remove temporary files
  rm -f $tmpFile.*

  exit 0
